//
//  GHStatusViewModel.swift
//  GHWeibo
//
//  Created by LGH on 2017/8/18.
//  Copyright © 2017年 LGH. All rights reserved.
//

import Foundation
import YYModel

class GHStatusViewModel {
    
    lazy var statusList = [GHStatus]()
    var pullupTimes = 0
    var maxPullupTime = 2
    
    func loadData(isPullup: Bool, completion: @escaping (Bool)->()) {
        
        //限制上拉刷新次数
        if isPullup == true {
            
            if pullupTimes > maxPullupTime {
                print("上拉刷新次数已被限制,已经刷了\(pullupTimes - 1)次")
                return
            }
            pullupTimes += 1
        }
        
        let since_id = (isPullup==true) ? 0 : (statusList.first?.id ?? 0)
        let max_id = (!isPullup==true) ? 0 : (statusList.last?.id ?? 0)
        GHNetworkManager.shared.loadStatusData(since_id: since_id, max_id: max_id) { (json, isSuccess) in
            
            print(json ?? "")
            guard let statusArr = NSArray.yy_modelArray(with: GHStatus.self, json: json ?? []) as? [GHStatus] else{
                
                completion(isSuccess)
                return
            }
            print("刷新了\(statusArr.count)条数据")
            if isPullup {
                
                self.statusList = self.statusList + statusArr

            }else{
                
                self.statusList = statusArr + self.statusList
            }
            
            completion(isSuccess)
        }
        
    }
}
